﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.Web.Security;
using System.DirectoryServices;
using Auction_Intranet.Models;
using AuctionDataLayer;
using Auction_Intranet.Helpers;
using System.Configuration;

namespace Auction_Intranet.Controllers
{
    [HandleError]
    public class DashboardController : ParentController
    {

        DataRepository m_rep = new DataRepository();
        //[RequireHttps]
        public ActionResult Index(long? ticks)
        {
            var username = (User.Identity.Name).Split('\\')[1];
            User user = m_rep.GetUserByUsername(username);
            var today = DateTime.Now;
            DashBoardInfoModel model;
            if (user != null)
            {
                DateTime requestedDate;
                if (ticks.HasValue)
                {
                    long ticksDate = ticks.Value;
                    requestedDate = new DateTime(ticksDate);
                }
                else
                {
                    requestedDate = DateTime.Now;
                }
                bool next = false;
                if (requestedDate.Hour > 20)
                {
                    next = true;
                    requestedDate = requestedDate.AddDays(1);
                }

                model = new DashBoardInfoModel();
                model.bidTimes = m_rep.GetAvailableBidTimes();
                model.rooms = m_rep.GetAllRooms();

                var MostPopularDate = DateTime.Now;
                if (requestedDate.Hour > 20)
                {
                    MostPopularDate = MostPopularDate.AddDays(2);
                }
                else
                {
                    MostPopularDate = MostPopularDate.AddDays(1);
                }
                IEnumerable<Bid> DayResultAll = m_rep.GetAllBidsByDate(MostPopularDate);
             
                //If date is more than current do not show any results
                //Important: ONLY GET ACCEPTED BIDS!!!!
                if (requestedDate.Date <= today.Date || next == true && requestedDate.Date <= today.AddDays(1).Date)
                {
                    model.DayResults = m_rep.GetBidResultByDate(requestedDate);
                }
                else
                {
                    model.DayResults = new List<Bid>();
                }
                var userBids = m_rep.GetUserBidByUserId(user.Id);
                model.PendingBids = userBids.Where(z => z.StateId == 1).OrderBy(y => y.Date).Take(5);
                model.PastBids = userBids.Where(z => z.StateId != 1).OrderByDescending(y => y.Date).Take(5);
                model.currentDateResult = requestedDate;

                MostlyBiddedHoursModel statmodel = new MostlyBiddedHoursModel();
                statmodel.date = MostPopularDate;                
                //create list of all bids for the date and theirs counts                
                List<HourStatisticModel> stats = new List<HourStatisticModel>();
                //var test = m_rep.GetAllPendingBidsByDate(new DateTime(2012,11,1));
                foreach (var item in model.bidTimes)
                {
                    HourStatisticModel temp = new HourStatisticModel();
                    temp.time = item.Startime.Hour.ToString() + ":" + item.Startime.ToString("mm");
                    temp.numberOFBids = DayResultAll.Where(x => x.StartTime <= item.Startime && x.EndTime >= item.Endtime && x.Id == x.AnyRoomId).Count();
                    stats.Add(temp);
                }
                statmodel.timeStatistics = stats;                
                model.MostlyBiddedHours = statmodel;
                return View(model);
            }
            return View();
        }

        public ActionResult IndexAJAX(string ticks)
        {
            var username = (User.Identity.Name).Split('\\')[1];
            User user = m_rep.GetUserByUsername(username);

            DashBoardInfoModelAJAX model;
            if (user != null)
            {
                DateTime requestedDate;
                if (ticks != "" && ticks != null)
                {
                    long ticksDate = Convert.ToInt64(ticks);
                    requestedDate = new DateTime(1970, 01, 01).AddMilliseconds(ticksDate);
                }
                else
                {
                    requestedDate = DateTime.Now;
                }

                //invalid date
                //If date is more than current do not show any results
                var today = DateTime.Now;
                if (requestedDate.Date > today.Date && today.Hour < 20 && requestedDate.AddDays(1).Date != today.AddDays(1).Date)
                {
                    return Json("", JsonRequestBehavior.AllowGet);
                }

                if (today.Hour >= 20 && requestedDate.Date > today.AddDays(1).Date)
                {
                    return Json("", JsonRequestBehavior.AllowGet);
                }
                             
                model = new DashBoardInfoModelAJAX();
                model.bidTimes = m_rep.GetAvailableBidTimes();
                model.rooms = m_rep.GetAllRooms();                    
                //Important: ONLY GET ACCEPTED BIDS!!!!
                model.DayResults = m_rep.GetBidResultByDate(requestedDate);
                //model.DayResults = m_rep.GetAllPendingBidsByDate(requestedDate);
                model.currentDateResult = requestedDate;

                List<object> result = new List<object>();                    
                foreach (var item in model.rooms)
                {
                    List<object> tempRoom = new List<object>();
                    foreach (var item2 in model.bidTimes)
                    {
                        var tempResult = model.DayResults.Where(x => x.RoomId == item.Id && x.StartTime == item2.Startime).FirstOrDefault();
                        if (tempResult != null)
                        {
                            int start = model.bidTimes.Where(x => x.Startime == (tempResult.StartTime)).Select(x => x.Id).FirstOrDefault();
                            int end = model.bidTimes.Where(x => x.Endtime == (tempResult.EndTime)).Select(x => x.Id).FirstOrDefault();
                            var bidItemClass = "bidentry be-size-" + (end - start + 1).ToString();

                            var gName = tempResult.Group.Name;
                            var tempTime = new { timeValue = gName, tempClass = bidItemClass };
                            tempRoom.Add(tempTime);
                        }
                        else
                        {
                            var tempTime = new { timeValue = "", tempClass = "" };
                            tempRoom.Add(tempTime);
                        }
                    }
                    result.Add(tempRoom);
                }
                return Json(result, JsonRequestBehavior.AllowGet);                                    
            }
            return Json("", JsonRequestBehavior.AllowGet);
        }

        public ActionResult ChartAJAX(string ticks)
        {
            var username = (User.Identity.Name).Split('\\')[1];
            User user = m_rep.GetUserByUsername(username);
            if (user != null)
            {
                DateTime requestedDate;
                if (ticks != "" && ticks != null)
                {
                    long ticksDate = Convert.ToInt64(ticks);
                    requestedDate = new DateTime(1970, 01, 01).AddMilliseconds(ticksDate);
                }
                else
                {
                    requestedDate = DateTime.Now;
                }
                var bidTimes = m_rep.GetAvailableBidTimes();             
                //create list of all bids for the date and theirs counts                
                List<object> stats = new List<object>();
                var bids = m_rep.GetAllBidsByDate(requestedDate);
                foreach (var item in bidTimes)
                {
                    //HourStatisticModel temp = new HourStatisticModel();
                    var ttime = item.Startime.Hour.ToString() + ":" + item.Startime.ToString("mm");
                    var tnumberOFBids = bids.Where(x => x.StartTime <= item.Startime && x.EndTime >= item.Endtime && x.Id == x.AnyRoomId).Count();
                    var tempEntry = new { time = ttime.ToString(), numberOFBids = tnumberOFBids.ToString() };
                    stats.Add(tempEntry);
                }
                return Json(stats, JsonRequestBehavior.AllowGet);
            }
            return Json("", JsonRequestBehavior.AllowGet);
        }
    }
}
